package com.cy.gameserver.webSockect;

import com.cy.gameserver.utils.SpringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

/**
 * Created by tiankai.qin on 18/3/9.
 */

@Component
@ServerEndpoint("/websocket/{token}")
public class WebSocketConnection {

    private WebSocketDispatcher webSocketDispatcher;

    private static final Logger logger = LoggerFactory.getLogger(WebSocketConnection.class);

    private Session session;

    @OnOpen
    public void onOpen(Session session, @PathParam(value = "token") String token) {
        this.session = session;
        this.webSocketDispatcher = (WebSocketDispatcher) SpringUtil.getBean("webSocketDispatcher");
        System.out.println("session id:" + session.getId() + " 来到了服务器");
        logger.info("session id:" + session.getId() + " 来到了服务器");
        webSocketDispatcher.onOpen(session, token);
    }

    @OnMessage
    public void onMessage(String message) {
        System.out.println("session id:" + session.getId() + " 发来了信息:" + message);
        logger.info("session id:" + session.getId() + " 发来了信息:" + message);
        webSocketDispatcher.onMessage(session, message);
    }

    @OnClose
    public void onClose() {
        logger.info("session id:" + session.getId() + " 离开了服务器");
        System.out.println("session id:" + session.getId() + " 离开了服务器");
        webSocketDispatcher.onClose(session);
    }

    @OnError
    public void onError(Throwable throwable) {
        webSocketDispatcher.onError(session, throwable);
    }

}
